
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)



与聊天相关的提示模板
====


[Chat Models](../models/chat)以聊天消息列表作为输入——这个列表通常称为提示。这些聊天消息与原始字符串（您将传递给[LLM](../models/llms)模型的字符串)不同，因为每个消息都与一个角色相关联。

例如，在OpenAI的[Chat Completion API](https://platform.openai.com/docs/guides/chat/introduction)中，聊天消息可以与AI、人类或系统角色相关联。模型应更密切地遵循系统聊天消息的指示。

因此，LangChain提供了几个相关的提示模板，以便轻松构建和处理提示。在查询聊天模型时，建议您使用这些与聊天相关的提示模板，而不是`PromptTemplate`，以充分发挥基础聊天模型的潜力。

```python
from langchain.prompts import (
    ChatPromptTemplate,
    PromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

```

要创建与角色相关联的消息模板，您可以使用 `MessagePromptTemplate`。

为了方便起见，在模板上公开了`from_template`方法。如果您要使用此模板，它的外观如下：

```python
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

```

如果您想更直接地构建`MessagePromptTemplate`，您可以在外部创建一个`PromptTemplate`，然后将其传递进去，例如：
```python
prompt=PromptTemplate(
    template="You are a helpful assistant that translates {input_language} to {output_language}.",
    input_variables=["input_language", "output_language"],
)
system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)

assert system_message_prompt == system_message_prompt_2

```
之后，您可以从一个或多个`MessagePromptTemplates`构建一个`ChatPromptTemplate`。

您可以使用`ChatPromptTemplate`的`format_prompt`方法 - 这将返回一个`PromptValue`，您可以将其转换为字符串或Message对象，具体取决于您是否想将格式化值用作llm或chat模型的输入。
```python
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# get a chat completion from the formatted messages
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()

```

```python
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={})]

```

输出的格式 Format output[#](#format-output "Permalink to this headline")
-------------------------------------------------------------

`format_prompt`方法的输出可以作为字符串、消息列表和`ChatPromptValue`使用。

作为字符串：

```python
output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")
output

```

```python
'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'

```

```python
# or alternatively 
output_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()

assert output == output_2

```

作为`ChatPromptValue`

```python
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.")

```

```python
ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})])

```

作为消息对象列表：

```python
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()

```

```python
[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
 HumanMessage(content='I love programming.', additional_kwargs={})]

```

不同类型的 `MessagePromptTemplate`[#](#different-types-of-messageprompttemplate "Permalink to this headline")
--------------------------------------------------------------------------------------------------------

LangChain 提供了不同类型的 `MessagePromptTemplate`。其中最常用的是 `AIMessagePromptTemplate`、`SystemMessagePromptTemplate` 和 `HumanMessagePromptTemplate`，分别用于创建 AI 消息、系统消息和人类消息。

但是，在聊天模型支持使用任意角色发送聊天消息的情况下，您可以使用 `ChatMessagePromptTemplate`，允许用户指定角色名称。

```python
from langchain.prompts import ChatMessagePromptTemplate

prompt = "May the {subject} be with you"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)
chat_message_prompt.format(subject="force")

```

```python
ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

```

LangChain 还提供了 `MessagesPlaceholder`，该占位符可以在格式化期间完全控制要呈现的消息。当您不确定应该使用哪个消息提示模板的角色或者希望在格式化期间插入消息列表时，这可能非常有用。

```python
from langchain.prompts import MessagesPlaceholder

human_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)

chat_prompt = ChatPromptTemplate.from_messages([MessagesPlaceholder(variable_name="conversation"), human_message_template])

```

```python
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn. 

2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.

3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")

chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()

```

```python
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),
 AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn.   2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.  3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),
 HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]

```

